<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator函数的for...of循环</title>
</head>
<body>
    <h1>Generator函数的for...of循环</h1>

    <script>
        // 基本用法
        function* foo() {
            yield 1;
            yield 2;
            yield 3;
            yield 4;
            yield 5;
            return 6;
        }

        for (let v of foo()) {
            console.log(v); // 1 2 3 4 5
        }

        // 使用Generator函数实现斐波那契数列
        function* fibonacci() {
            let [prev, curr] = [0, 1];
            for (;;) {
                yield curr;
                [prev, curr] = [curr, prev + curr];
            }
        }

        // 输出斐波那契数列前10个数字
        for (let n of fibonacci()) {
            if (n > 100) break;
            console.log(n);
        }

        // 为对象添加遍历器接口
        function* objectEntries() {
            let propKeys = Object.keys(this);
            for (let propKey of propKeys) {
                yield [propKey, this[propKey]];
            }
        }

        let jane = { first: 'Jane', last: 'Doe' };
        jane[Symbol.iterator] = objectEntries;

        for (let [key, value] of jane) {
            console.log(`${key}: ${value}`);
        }
    </script>
</body>
</html> 